package com.xxy.stack;

import java.util.Scanner;

/**
 * @author xxy
 * @create 2020 11 04 22:43
 * 栈：先进后出，只能对栈顶进行操作，经典的操作就是押栈（push）和出栈（pop)
 * 用数组模拟栈：
 *    定义一个top来表示栈顶，初始化为-1，
 *    入栈的操作：当有数据加入到栈时，top++;stack[top] = data;
 *    出栈的操作：int value = stack[top];top--;return value;
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(4);
        String key = " ";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);
        while (loop){
            System.out.println("show：表示显示栈");
            System.out.println("exit：退出程序");
            System.out.println("push：表示添加元素到栈中（入栈）");
            System.out.println("pop：表示从栈输出（出栈）");
            System.out.println("请输入你的选择");
            key = scanner.next();
            switch (key){
                case "show":
                    arrayStack.list();
                    break;
                case "exit":
                    loop = false;
                    break;
                case "push":
                    int value =scanner.nextInt();
                    arrayStack.push(value);
                    break;
                case "pop":
                    try {
                        int temp =arrayStack.pop();
                        System.out.println("出栈元素为"+temp);

                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
            }
        }
    }
}
//定义一个ArrayStack 表示栈
  class ArrayStack {
    private int maxSize;//栈的大小
    private int[] stack;//数组模拟栈
    private int top = -1;//top表示栈顶，初始化为-1
    //构造器
    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        stack = new int [maxSize];
    }
    //判断栈满
    public boolean isFull(){
        return top ==maxSize-1;
    }
    //判断栈为空
    public boolean isEmpty(){
        return top==-1;
    }
    //入栈
    public void push(int data){
        //先判断是否满
        if(isFull()){
            return;
        }
        top++;
        stack[top]=data;
    }
    //出栈
    public int pop(){
        //先判断是否为空
        if(isEmpty()){
            throw new RuntimeException("栈空");
        }
        int value=stack[top];
        top--;
        return value;
    }
    //遍历栈
    public void list(){
        //从栈顶开始遍历，先看是否为空
        if(isEmpty()){
            return;
        }
        for(int i=top;i>=0;i--){
            System.out.println(" stack["+i+"]="+stack[i]);
        }
        System.out.println();
    }
}
